package com.yboot.starter.holiday.core.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yboot.starter.holiday.core.HolidaySynchronizerService;
import com.yboot.starter.holiday.core.vo.HolidayResponseVo;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 功能描述
 *
 * @author yangcs
 * @date 2025/8/6
 */
@Slf4j
public class DefaultHolidaySynchronizer implements HolidaySynchronizerService {

    private String url;

    public DefaultHolidaySynchronizer(String url) {
        this.url = url;
    }

    // 解析请求结果
    public List<HolidayResponseVo> syncHoliday(String year) {
        String body = getHolidayOnLine(year);
        Map<String, HolidayResponseVo> holidayMap = JSONObject.parseObject(body, new TypeReference<Map<String, HolidayResponseVo>>() {
        });
        List<HolidayResponseVo> list = new ArrayList<>();
        for (String key : holidayMap.keySet()) {
            HolidayResponseVo value = holidayMap.get(key);
            list.add(value);
        }
        return list;
    }

    /**
     * 在线获取节假日
     * @param year
     * @return
     */
    private String getHolidayOnLine(String year) {
        String body = "";
        // 创建OkHttpClient实例
        OkHttpClient client = new OkHttpClient();
        String requestUrl = url + year;
        Request request = new Request.Builder().url(requestUrl).get().build();
        try {
            Response response = client.newCall(request).execute();
            body = response.body().string();
            log.info("拉取节假日发起请求：{} \n 响应结果: {}", requestUrl, body);
        } catch (IOException e) {
            log.info("拉取节假日请求异常：{} \n 响应结果: {}", requestUrl, e.getMessage());
            throw new RuntimeException(e);
        }
        return body;
    }


}
